package com.sf.asp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sf.asp.entity.Role;
import com.sf.asp.entity.UserRole;
import com.sf.asp.dao.UserRoleMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.asp.entity.vo.RoleVO;
import com.sf.asp.service.RoleService;
import com.sf.asp.service.UserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jins
 * @since 2021-11-24
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {


    private final RoleService roleService;

    private final UserRoleMapper userRoleMapper;

    public UserRoleServiceImpl(RoleService roleService,UserRoleMapper userRoleMapper){
        this.roleService = roleService;
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public List<RoleVO> listRoleByUserId(Integer userId) {
        List<RoleVO> roles = roleService.listRoleForUser();
        LambdaQueryWrapper<UserRole> query = new LambdaQueryWrapper<>();
        query.eq(UserRole::getUserId,userId);
        List<UserRole> userRoles = userRoleMapper.selectList(query);
        if (userRoles == null || userRoles.isEmpty()){
            return roles;
        }

        List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        roles.forEach(roleVO -> {
            if (roleIds.contains(roleVO.getId())){
                roleVO.setCheck(true);
            }
        });
        return roles;
    }
}
